package com.xuqm.base.web

import android.Manifest
import android.annotation.SuppressLint
import android.app.DownloadManager
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.webkit.URLUtil
import android.webkit.ValueCallback
import androidx.lifecycle.ViewModelProvider
import com.bigkoo.alertview.AlertView
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.ml.scan.HmsScan
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.xuqm.base.R
import com.xuqm.base.common.FileHelper
import com.xuqm.base.common.GlideEngine
import com.xuqm.base.common.LogHelper
import com.xuqm.base.databinding.ActivityXWebviewBinding
import com.xuqm.base.extensions.loge
import com.xuqm.base.extensions.runWithPermission
import com.xuqm.base.extensions.showMessage
import com.xuqm.base.ui.BaseActivity
import java.io.File


class XWebViewActivity : BaseActivity<ActivityXWebviewBinding>() {
    private lateinit var title: String
    private lateinit var url: String
    private var hasTopBar: Boolean = true


    private lateinit var viewModel: XWebViewModel

    override fun getLayoutId(): Int = R.layout.activity_x_webview

    @SuppressLint("SetJavaScriptEnabled")
    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        LogHelper.e("initView")
        showBack(false)
        baseBinding.baseToolbar.closeBtn.visibility = View.VISIBLE
        baseBinding.baseToolbar.closeBtn.setOnClickListener { finish() }

        viewModel = ViewModelProvider(this)[XWebViewModel::class.java]

        viewModel.activity = this
        viewModel.callBack = XWebCallBack(binding.XWebView)

        binding.XWebView.webChromeClient = XWebChromeClient(this, viewModel)
        binding.XWebView.webViewClient = XWebViewClient()
        binding.XWebView.clearCache(true)
        binding.XWebView.settings.javaScriptEnabled = true
        binding.XWebView.settings.setGeolocationEnabled(true)
        binding.XWebView.addJavascriptInterface(
            XAndroidInterface(mContext, viewModel),
            "ZHHBAndroid"
        )
        binding.XWebView.setDownloadListener { url, _, contentDisposition, mimeType, _ ->

            downloadBySystem(url, contentDisposition, mimeType)
        }
    }

    override fun initData() {
        super.initData()
        LogHelper.e("initData")
        intent?.apply {
            title = getStringExtra("title") ?: ""
            url = getStringExtra("url") ?: ""
            hasTopBar = getBooleanExtra("hasTopBar", true)
        }

        viewModel.title.observe(this, {
//            if(ToolsHelper.isNull(it)){
//                baseBinding.baseToolbar.visibility=View.GONE
//            }else{
//                baseBinding.baseToolbar.visibility=View.VISIBLE
            setTitleText(it)
//            }
        })
        viewModel.progress.observe(this, {
            binding.XProgressBar.progress = it
            if (it > 90) {
                binding.XProgressBar.visibility = View.GONE
            } else {
                binding.XProgressBar.visibility = View.VISIBLE
            }
        })

    }

    override fun lateInitView() {
        super.lateInitView()
        LogHelper.e("lateInitView")
        LogHelper.e(url)
        setTitleText(title)
        binding.XWebView.loadUrl(url)

    }

    override fun backBtnPressed() {
        if (binding.XWebView.canGoBack()) {
            binding.XWebView.goBack()
        }
    }

    override fun onBackPressed() {
        if (binding.XWebView.canGoBack()) {
            binding.XWebView.goBack()
        }
    }

    private lateinit var filePathCallback: ValueCallback<Array<Uri>>

    fun selectedFile(types: String, back: ValueCallback<Array<Uri>>) {
        filePathCallback = back

        if (types.contains("image")) {
            runWithPermission(
                Manifest.permission.CAMERA,
                rationaleMethod = {
                    "无法获取相关权限".showMessage()
                    back.onReceiveValue(null)
                },
                permanentDeniedMethod = {
                    "请在设置界面开放对应权限".showMessage()
                    back.onReceiveValue(null)
                },
                callback = {
                    PictureSelector.create(mContext)
                        .openGallery(PictureMimeType.ofAll())
//                    .setPictureUIStyle(mPictureParameterStyle)
                        .imageEngine(GlideEngine.createGlideEngine())
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: MutableList<LocalMedia>) {
                                val results =
                                    result.map { FileHelper.getFileUri(File(it.realPath)) }
                                back.onReceiveValue(results.toTypedArray())
                            }

                            override fun onCancel() {
                                back.onReceiveValue(null)
                            }
                        })
                })
        } else {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = types
            }
            mContext.startActivityForResult(intent, 10012)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 10012) {
            if (resultCode == RESULT_OK) {
                data?.data?.also { uri ->
                    filePathCallback.onReceiveValue(arrayOf(uri))
                }
            } else {
                filePathCallback.onReceiveValue(emptyArray())
            }
        } else if (requestCode == 1111) {


            if (resultCode == RESULT_OK) {
                val obj: HmsScan? = data?.getParcelableExtra(ScanUtil.RESULT)
                if (obj != null) {
                    viewModel.backScan(obj.originalValue)
                } else {
                    viewModel.backScanError()
                }
            } else {
                viewModel.backScan("取消")
            }

        }

    }

    private fun downloadBySystem(url: String, contentDisposition: String, mimeType: String) {
        val request = DownloadManager.Request(Uri.parse(url))

        val fileName: String = URLUtil.guessFileName(url, contentDisposition, mimeType)
        fileName.loge()

//        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
        // 设置通知栏的标题，如果不设置，默认使用文件名
//        request.setTitle(BuildConfig.APP_Name);
        // 设置通知栏的描述
        request.setDescription("正在下载文件:${fileName}");
        // 允许在计费流量下下载
        request.setAllowedOverMetered(false)
        // 允许该记录在下载管理界面可见
        request.setVisibleInDownloadsUi(true)
        // 允许漫游时下载
        request.setAllowedOverRoaming(true)
        // 允许下载的网路类型
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
        // 设置下载文件保存的路径和文件名
        val file = File(FileHelper.getDownloadPath(), fileName)
        request.setDestinationUri(Uri.fromFile(file))
        val downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager
        // 添加一个下载任务
        val downloadId = downloadManager.enqueue(request)
        downloadId.loge()

        AlertView(
            "", "当前文件已经开始下载，请查看通知栏下载进度", null, arrayOf("确定"), null, mContext,
            AlertView.Style.Alert
        ) { _, _ ->
        }.show()
    }

}